package com.visikard.ui.activity;

import java.io.FileNotFoundException;
import java.io.IOException;

import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.os.Message;
import android.provider.MediaStore;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.view.View;
import android.view.Window;
import android.view.inputmethod.InputMethodManager;
import android.widget.Toast;

import com.visikard.application.UIMessage;
import com.visikard.application.VKRegApplication;
import com.visikard.asynctask.BaseTask;
import com.visikard.asynctask.CreateCouponTask;
import com.visikard.asynctask.GetDetailCouponTask;
import com.visikard.asynctask.UpdateCouponTask;
import com.visikard.asynctask.UploadCBImageTask;
import com.visikard.item.ItemCouponsBuilder;
import com.visikard.item.ItemCouponsBuilderCreate;
import com.visikard.ui.R;
import com.visikard.ui.fragment.CBDetailFragment;
import com.visikard.ui.fragment.CBEffectFragment;
import com.visikard.ui.fragment.CBPreviewBuilderFragment;
import com.visikard.ui.fragment.KBCamera24Fragment;
import com.visikard.ui.fragment.ViewClickable;
import com.visikard.utility.BitmapUtils;

public class CouponBuilderActivity extends BaseLoginCompleteActivity implements ViewClickable,
		KBCamera24Fragment.OnImagePickedListener {

	public static final String EXT_DATA_EDIT_ITEM = "CouponBuilderActivity_ext_data_edit_item";

	public static final int REQUEST_CODE_CREATE_UPDATE_COUPON = 1;

	private FragmentManager fmManager;
	private FragmentTransaction fmTransaction;

	public static Bitmap couponBitmap;

	public static ItemCouponsBuilderCreate itemCouponBuilderCreate;

	public enum CouponAction {
		CREATE, UPDATE;
	}

	private CouponAction mAction;

	private BaseTask mAsyncTask;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.coupon_builder_24);

		// hide content while waiting for camera nitial - solve sony xperia neol problem
		getWindow().getDecorView().findViewById(android.R.id.content).setVisibility(View.INVISIBLE);

		fmManager = getSupportFragmentManager();

		itemCouponBuilderCreate = null;
		couponBitmap = null;
		if (getIntent().getExtras() != null && getIntent().getExtras().getSerializable(EXT_DATA_EDIT_ITEM) != null) {
			ItemCouponsBuilder item = (ItemCouponsBuilder) getIntent().getExtras().getSerializable(EXT_DATA_EDIT_ITEM);
			getCouponDetail(Integer.parseInt(String.valueOf(item.getIdCampaignSpecail())));
		}
		else {
			putFragment(new KBCamera24Fragment());
		}
	}

	@Override
	protected void onDestroy() {
		itemCouponBuilderCreate = null;
		couponBitmap = null;
		System.gc();
		super.onDestroy();
	}

	/**
	 * put a fragment with UI
	 */
	public void putFragment(Fragment fm) {
		fmTransaction = fmManager.beginTransaction();
		fmTransaction.setCustomAnimations(R.anim.push_left_in, 0, 0, R.anim.push_right_out);
		fmTransaction.add(R.id.kb_content_cover, fm);
		fmTransaction.addToBackStack(null);
		fmTransaction.commit();
	}

	public void popFragment() {
		fmManager.popBackStack();
	}

	public void showProgressDialog() {
		if (mProgress == null) {
			mProgress = new Dialog(CouponBuilderActivity.this, android.R.style.Theme_Translucent_NoTitleBar);
			mProgress.setContentView(R.layout.progressdialog);
			mProgress.setCancelable(false);
		}

		mProgress.show();
	}

	public void dismissProgressDialog() {
		if (mProgress != null && mProgress.isShowing()) {
			mProgress.dismiss();
		}
	}

	@Override
	public void onBackPressed() {
		if (fmManager.findFragmentById(R.id.kb_content_cover) instanceof KBCamera24Fragment)
			finish();
		else
			super.onBackPressed();
	}

	/**
	 * do get info and go to next screen
	 */
	public void nextFragment() {
		hideKeyboard();
		try {
			Fragment fm = fmManager.findFragmentById(R.id.kb_content_cover);
			if (fm instanceof KBCamera24Fragment) {
				if (CouponBuilderActivity.couponBitmap != null) {
					CBEffectFragment cbEffectFragment = new CBEffectFragment();
					putFragment(cbEffectFragment);
				}
				else {
					if (itemCouponBuilderCreate != null) {
						CBEffectFragment cbEffectFragment = new CBEffectFragment();
						Bundle args = new Bundle();
						args.putString(CBEffectFragment.EXT_DATA_URI, itemCouponBuilderCreate.getImageSpecial());
						cbEffectFragment.setArguments(args);
						putFragment(cbEffectFragment);
					}
					else {
						putFragment(new CBEffectFragment());
					}
				}
			}
			else if (fm instanceof CBEffectFragment) {
				putFragment(new CBDetailFragment());
			}
			else if (fm instanceof CBDetailFragment) {
				putFragment(new CBPreviewBuilderFragment());
			}

		}
		catch (Exception e) {
			e.printStackTrace();
		}
	}

	private void hideKeyboard() {
		InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
		imm.hideSoftInputFromWindow(getWindow().findViewById(Window.ID_ANDROID_CONTENT).getWindowToken(), 0);
	}

	@Override
	public void onViewClick(View v) {
		switch (v.getId()) {
			default:
				try {
					Fragment fm = fmManager.findFragmentById(R.id.kb_content_cover);
					if (fm instanceof ViewClickable) {
						((ViewClickable) fm).onViewClick(v);
					}
				}
				catch (Exception e) {
					e.printStackTrace();
				}
				break;
		}
	}

	@Override
	public void onImagePicked(Uri uri) {
		Fragment fm = fmManager.findFragmentById(R.id.kb_content_cover);
		if (fm instanceof KBCamera24Fragment) {
			if (uri.getScheme().contains("http")) {
				couponBitmap = null;
			}
			else {
				try {
					Bitmap bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), uri);
					couponBitmap = bitmap;
				}
				catch (FileNotFoundException e) {
					e.printStackTrace();
				}
				catch (IOException e) {
					e.printStackTrace();
				}
			}
			nextFragment();
		}
	}

	public void createCoupon() {
		if (itemCouponBuilderCreate != null) {
			mAction = CouponAction.CREATE;
			mAsyncTask = new UploadCBImageTask(mHandler, false);
			mAsyncTask.execute(VKRegApplication.uid, BitmapUtils.getByteArrayOutputStream(couponBitmap, 100));
			mHandler.sendEmptyMessage(UIMessage.MSG_CREATE_UPDATE_COUPON_START);
		}
	}

	public void updateCoupon() {
		if (itemCouponBuilderCreate != null && itemCouponBuilderCreate.getCouponID() > 0) {
			mAction = CouponAction.UPDATE;
			mAsyncTask = new UploadCBImageTask(mHandler, false);
			mAsyncTask.execute(VKRegApplication.uid, BitmapUtils.getByteArrayOutputStream(couponBitmap, 100));
			mHandler.sendEmptyMessage(UIMessage.MSG_CREATE_UPDATE_COUPON_START);
		}
	}

	public void getCouponDetail(int couponID) {
		mAsyncTask = new GetDetailCouponTask(mHandler, false);
		mAsyncTask.execute(VKRegApplication.uid, couponID);
		mHandler.sendEmptyMessage(UIMessage.MSG_GET_COUPON_DETAIL_START);
	}

	@Override
	public boolean handleMessage(Message msg) {
		switch (msg.what) {
			case UIMessage.MSG_UPLOAD_CBIMAGE_COMPLETE:
				String imageResult = (String) msg.obj;
				if (!imageResult.equals("")) {
					itemCouponBuilderCreate.setImageSpecial(imageResult);
					if (mAction == CouponAction.CREATE) {
						mAsyncTask = new CreateCouponTask(mHandler, false);
						mAsyncTask.execute(VKRegApplication.uid, itemCouponBuilderCreate);
					}
					else {
						mAsyncTask = new UpdateCouponTask(mHandler, false);
						mAsyncTask.execute(VKRegApplication.uid, itemCouponBuilderCreate);
					}
				}
				return true;
			case UIMessage.MSG_CREATE_UPDATE_COUPON_START:
				showProgressDialog();
				return true;
			case UIMessage.MSG_CREATE_UPDATE_COUPON_FINISH:
				dismissProgressDialog();
				if (msg != null) {
					int result = msg.arg1;
					if (result == 1) {
						Toast.makeText(getApplicationContext(), R.string.success, Toast.LENGTH_SHORT).show();
						setResult(Activity.RESULT_OK);
						finish();
					}
					else {
						Toast.makeText(getApplicationContext(), R.string.fail, Toast.LENGTH_SHORT).show();
					}
				}
				return true;
			case UIMessage.MSG_GET_COUPON_DETAIL_START:
				showProgressDialog();
				return true;
			case UIMessage.MSG_GET_COUPON_DETAIL_FINISH:
				dismissProgressDialog();

				itemCouponBuilderCreate = (ItemCouponsBuilderCreate) msg.obj;
				if (itemCouponBuilderCreate != null) {
					Bundle args = new Bundle();
					args.putString(CBEffectFragment.EXT_DATA_URI, itemCouponBuilderCreate.getImageSpecial());
					KBCamera24Fragment camera24Fragment = new KBCamera24Fragment();
					camera24Fragment.setArguments(args);
					putFragment(camera24Fragment);
				}
				else {
					Toast.makeText(getApplicationContext(), R.string.fail, Toast.LENGTH_SHORT).show();
					finish();
				}
				return true;
		}
		return super.handleMessage(msg);
	}

}
